<template>
  <d2-container>
    <template slot="header">
      <el-form
        :inline="true"
        :model="queryForm"
        ref="queryForm"
        size="mini"
        style="margin-bottom: -18px;"
      >
        <el-form-item label="统计区域" prop="areaName">
          <el-input
            v-model="queryForm.areaName"
            placeholder="用户"
            style="width: 100px;"
            :disabled="true"
          />
        </el-form-item>

        <el-form-item label prop="type">
          <el-select v-model="queryForm.type" placeholder="请选择" style="width: 100px;">
            <el-option
              v-for="(item, index) in queryForm.selectOption"
              :key="index"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label prop="searchVal">
          <el-input v-model="queryForm.searchVal" placeholder="请输入" style="width: 100px;" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleFormSubmit">
            <d2-icon name="search" />查询
          </el-button>
        </el-form-item>
      </el-form>
    </template>
    <split-pane :min-percent="10" :max-percent="20" :default-percent="20" split="vertical">
      <template slot="paneL">
        <my-area-tree @change="onAreaChange" />
      </template>
      <template slot="paneR">
        <d2-crud
          ref="d2Crud"
          selection-row
          @selection-change="handleSelectionChange"
          :columns="columns"
          :data="data"
          :loading="loading"
          :pagination="pagination"
          @pagination-current-change="paginationCurrentChange"
        >
          <el-button size="mini" slot="header" style="margin-bottom: 5px" @click="addRow">新增</el-button>
          <el-button size="mini" slot="header" style="margin-bottom: 5px" @click="deleteRows">删除</el-button>
          <el-button size="mini" slot="header" style="margin-bottom: 5px">导入添加户号</el-button>
          <el-button size="mini" slot="header" style="margin-bottom: 5px">导入更新户号</el-button>
        </d2-crud>
      </template>
    </split-pane>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="63%"
      top="10vh"
      :before-close="handleClose"
    >
      <el-form
        :model="dialogForm"
        ref="dialogForm"
        size="mini"
        style="margin-bottom: -18px;width:825px"
        :rules="rules"
        :inline-message="true"
      >
        <div class="dialogInfoBox">
          <div class="dialogInfo">
            <el-form-item label="客户名称" prop="customerName" label-width="110px">
              <el-input v-model="dialogForm.customerName" placeholder="请输入" style="width: 220px;" />
            </el-form-item>
            <el-form-item label="客户户号" prop="householdIdList" label-width="110px">
              <!-- <el-autocomplete
                style="width: 220px;;"
                class="inline-input"
                v-model="dialogForm.householdName"
                :fetch-suggestions="querySearch"
                placeholder="请输入内容"
                @select="handleSelect"
              ></el-autocomplete>-->
              <el-select
                v-model="dialogForm.householdIdList"
                placeholder="请选择"
                style="width: 220px;"
                multiple
                filterable
              >
                <el-option
                  v-for="(item, index) in dialogForm.selectOption.householdList"
                  :key="index"
                  :label="item.householdName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </div>
          <div class="dialogInfo">
            <el-form-item label="证件类型" prop="customerCertificateType" label-width="110px">
              <el-select
                v-model="dialogForm.customerCertificateType"
                placeholder="请选择"
                style="width: 220px;"
              >
                <el-option
                  v-for="(item, index) in dialogForm.selectOption.certificate"
                  :key="index"
                  :label="item.valueName"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="证件号码" prop="customerCertificateNumber" label-width="110px">
              <el-autocomplete
                style="width: 220px;;"
                class="inline-input"
                v-model="dialogForm.customerCertificateNumber"
                :fetch-suggestions="querySearch1"
                placeholder="请输入内容"
                @select="handleSelect1"
              ></el-autocomplete>
            </el-form-item>
          </div>
          <div class="dialogInfo">
            <el-form-item label="客户编号" prop="customerSerialnumber" label-width="110px">
              <el-input
                v-model="dialogForm.customerSerialnumber"
                disabled
                placeholder="请输入"
                style="width: 220px;"
              />
            </el-form-item>
            <!-- <el-form-item label="客户状态" prop="customerState" label-width="110px">
              <el-select v-model="dialogForm.customerState" placeholder="请选择" style="width: 220px;">
                <el-option
                  v-for="(item, index) in dialogForm.selectOption.customerState"
                  :key="index"
                  :label="item.desc"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>-->
            <el-form-item label="客户类型" prop="customerType" label-width="110px">
              <el-select v-model="dialogForm.customerType" placeholder="请选择" style="width: 220px;">
                <el-option
                  v-for="(item, index) in dialogForm.selectOption.customerType"
                  :key="index"
                  :label="item.desc"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </div>
          <div class="dialogInfo">
            <el-form-item label="手机号码" prop="customerPhone" label-width="110px">
              <el-input v-model="dialogForm.customerPhone" placeholder="请输入" style="width: 220px;" />
            </el-form-item>
            <el-form-item label="客户固话" prop="customerTel" label-width="110px">
              <el-input v-model="dialogForm.customerTel" placeholder="请输入" style="width: 220px;" />
            </el-form-item>
          </div>
          <div class="dialogInfo">
            <el-form-item label="客户邮箱" prop="customerEmail" label-width="110px">
              <el-input v-model="dialogForm.customerEmail" placeholder="请输入" style="width: 220px;" />
            </el-form-item>
            <!-- <el-form-item label="启用状态" prop="customerUseState" label-width="110px">
              <el-select
                v-model="dialogForm.customerUseState"
                placeholder="请选择"
                style="width: 220px;"
              >
                <el-option
                  v-for="(item, index) in dialogForm.selectOption.enabledState"
                  :key="index"
                  :label="item.valueName"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>-->
          </div>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="saveDialog('dialogForm')">确 定</el-button>
      </span>
    </el-dialog>
  </d2-container>
</template>

<script>
import util from "@/libs/util";
import MyAreaTree from "@/components/my-area-tree";
import { Divider } from "element-ui";
import { xor } from "lodash";

export default {
  name: "areaArchives",
  components: { MyAreaTree },

  data() {
    return {
      householdName: "",
      customerCertificateNumber: "",
      // dialogForm: {},
      dialogTitle: "添加",
      dialogVisible: false,
      editFlag: false,
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 100,
        total: 0
      },
      queryForm: {
        areaId: "1",
        areaName: "中国",
        type: 0,
        searchVal: "",
        selectOption: []
      },
      columns: [
        {
          title: "序号",
          key: "serialNum",
          width: 50
        },
        {
          title: "客户名称",
          key: "customerName",
          sortable: true
        },
        {
          title: "客户类型",
          key: "customerTypeName",
          sortable: true
        },
        {
          title: "客户编号",
          key: "customerSerialnumber",
          sortable: true
        },
        {
          title: "户号信息",
          key: "houseHoldNames",
          sortable: false
        },
        {
          title: "操作",
          key: "",
          component: {
            render: (h, row, node, index) => {
              return (
                <div>
                  <button
                    class="el-button el-button--default el-button--mini"
                    onclick={() => {
                      this.handleDialogOpen(row);
                    }}
                  >
                    修改
                  </button>
                  <button
                    class="el-button el-button--danger el-button--mini"
                    onclick={() => {
                      this.handleRowRemove(row);
                    }}
                  >
                    删除
                  </button>
                </div>
              );
            }
          }
        }
      ],
      data: [],
      treeData: [],
      values: [],
      selectParams: {
        size: "mini"
      },
      selectionRow: [],
      treeParams: {
        "default-expand-all": true,
        data: [],
        props: {
          children: "children",
          label: "name",
          value: "id"
        }
      },
      formOptions: {
        labelWidth: "80px",
        labelPosition: "left",
        saveLoading: false
      },
      rules: {
        customerName: [{ required: true, message: "必填", trigger: "blur" }], // 客户名称
        // customerType: [{ required: true, message: '必填', trigger: 'blur' }], // 客户类型
        // customerState: [{ required: true, message: '必填', trigger: 'blur' }], // 客户状态
        customerSerialnumber: [
          { required: true, message: "必填", trigger: "blur" }
        ], // 客户编号
        customerCertificateType: [
          { required: true, message: "必填", trigger: "blur" }
        ], // 证件类型
        customerCertificateNumber: [
          { required: true, message: "必填", trigger: "blur" }
        ], // 证件编号
        householdIdList: [{ required: true, message: "必填", trigger: "blur" }], // 客户户号
        measureEquipConcent: [
          { required: true, message: "必填", trigger: "blur" }
        ], // 集中器
        collectChannel: [{ required: true, message: "必填", trigger: "blur" }], // 采集器通道
        measureBillingType: [
          { required: true, message: "必填", trigger: "blur" }
        ], // 计费类型
        measureParamPrice: [
          { required: true, message: "必填", trigger: "blur" }
        ], // 价格方案
        measureControlType: [
          { required: true, message: "必填", trigger: "blur" }
        ], // 控制方式
        measureOverdraftMoney: [
          { required: true, message: "必填", trigger: "blur" }
        ], // 透支金额
        measureWarnMoney: [
          { required: true, message: "必填", trigger: "blur" }
        ], // 告警金额
        serialnumber: [{ required: true, message: "必填", trigger: "blur" }], // 表计地址
        sysconfigMeterModel: [
          { required: true, message: "必填", trigger: "blur" }
        ], // 表计型号
        runstate: [{ required: true, message: "必填", trigger: "blur" }] // 表计型号
      },
      archiveList: [],
      dialogForm: {
        id: "",
        selectOption: {},
        customerName: "",
        customerType: "",
        customerSerialnumber: "",
        customerState: "",
        customerPhone: "",
        customerTel: "",
        customerCertificateType: "",
        customerCertificateNumber: "",
        customerEmail: "",
        customerUseState: "",
        householdIdList: []
      },
      oldHouseholdIdList: []
    };
  },
  mounted() {
    this.getArchiveList();
    this.getEquipmentType();
    this.fetchData();
    this.dialogForm.customerSerialnumber = "USER" + new Date().getTime();
  },
  methods: {
    // 获取档案信息列表
    getArchiveList() {
      const params = {
        areaOrg: 0
      };
      this.$api
        .admin_areaArchives_getList({
          ...params
        })
        .then(res => {
          this.archiveList = res;
        })
        .catch(err => {
          console.log("err", err);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleSelect1(item) {
      this.dialogForm.customerCertificateNumber =
        item.customerCertificateNumber;
      this.dialogForm.customerName = item.customerName;
      this.dialogForm.customerType = item.customerType;
      // this.dialogForm.customerSerialnumber = item.customerSerialnumber
      this.dialogForm.customerPhone = item.customerPhone;
      this.dialogForm.customerTel = item.customerTel;
      this.dialogForm.customerCertificateType = item.customerCertificateType;
      this.dialogForm.customerEmail = item.customerEmail;
    },
    querySearch1(queryString, cb) {
      // const restaurants = this.serialnumberList
      this.archiveList.map(h => {
        h.value = h.customerCertificateNumber;
      });
      const restaurants = this.archiveList;
      const results = queryString
        ? restaurants.filter(this.createFilter1(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter1(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    handleSelect(item) {
      this.dialogForm.householdNum = item.id;
    },
    querySearch(queryString, cb) {
      // const restaurants = this.serialnumberList
      this.dialogForm.selectOption.householdList.map(h => {
        h.value = h.householdName;
      });
      const restaurants = this.dialogForm.selectOption.householdList;
      const results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    // 保存信息
    saveDialog(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let randomNum = Math.random(0, 1) + "";

          const saveObj = {
            customerName: this.dialogForm.customerName,
            customerType: this.dialogForm.customerType,
            customerSerialnumber: this.dialogForm.customerSerialnumber,
            customerState: this.dialogForm.customerState,
            customerPhone: this.dialogForm.customerPhone,
            customerTel: this.dialogForm.customerTel,
            customerCertificateType: this.dialogForm.customerCertificateType,
            customerCertificateNumber: this.dialogForm
              .customerCertificateNumber,
            customerEmail: this.dialogForm.customerEmail,
            householdIdList: this.dialogForm.householdIdList,
            customerUseState: this.dialogForm.customerUseState,
            id: this.dialogForm.id
          };
          if (this.editFlag) {
            this.cancelBinding(saveObj);
          } else {
            saveObj.id = "";
            saveObj.measureAreaOrg = this.queryForm.areaId;

            this.handleRowAdd(saveObj);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 关闭弹框
    handleClose() {
      this.dialogVisible = false;
    },
    handleSelectionChange(selection) {
      this.selectionRow = selection;
    },
    deleteRows() {
      this.$confirm("确定删除吗?", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error"
      }).then(() => {
        this.$api
          .admin_areaArchives_delete(this.selectionRow.map(item => item.id))
          .then(res => {
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.fetchData();
          });
      });
    },
    // 删除row数据
    handleRowRemove(row) {
      this.$confirm("确定删除吗?", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error"
      }).then(() => {
        this.$api.admin_areaArchives_delete([row.id]).then(res => {
          this.$message({
            message: "删除成功",
            type: "success"
          });
          this.fetchData();
        });
      });
    },
    handleDialogOpen(row) {
      this.dialogTitle = "修改-" + row.customerName;
      this.editFlag = true;
      this.dialogVisible = true;
      this.$api.admin_areaArchives_get({ id: row.id }).then(res => {
        const selectOption = JSON.parse(
          JSON.stringify(this.dialogForm.selectOption)
        );
        this.dialogForm = res;
        this.oldHouseholdIdList = res.householdIdList;
        this.dialogForm.selectOption = selectOption;
      });
    },
    cancelBinding(row) {
      let ids = xor(this.oldHouseholdIdList,this.dialogForm.householdIdList);
      this.$api
        .admin_areaArchives_cancleBinding(ids)
        .then(res => {
          this.handleRowEdit(row);
        })
        .finally(() => {
          
        });
    },
    // 修改row数据
    handleRowEdit(row) {
      this.formOptions.saveLoading = true;
      this.$api
        .admin_areaArchives_update(row)
        .then(res => {
          this.$message({
            message: "保存成功",
            type: "success"
          });
          this.handleFormSubmit();
          this.dialogVisible = false;
        })
        .finally(() => {
          this.formOptions.saveLoading = false;
        });
    },
    // 新增数据
    addRow() {
      this.generateArchivesNum(this.queryForm.areaName);
    },
    //获取客户编号
    generateArchivesNum(areaName) {
      this.$api
        .admin_areaArchives_generateArchivesNum({
          orgName: areaName
        })
        .then(res => {
          let mySelectOption = JSON.parse(
            JSON.stringify(this.dialogForm.selectOption)
          );
          this.dialogForm = {
            customerName: "",
            customerType: "",
            customerSerialnumber: res,
            customerState: "",
            customerPhone: "",
            customerTel: "",
            customerCertificateType: "",
            customerCertificateNumber: "",
            customerEmail: "",
            householdNum: "",
            customerUseState: "",
            selectOption: mySelectOption
          };
          // 修改状态
          this.editFlag = false;
          this.dialogVisible = true;
          this.dialogTitle = "添加";
          const templateObj = {};
          this.$refs.d2Crud.setFormData(templateObj);
        });
    },
    handleRowAdd(row) {
      const params = row;
      this.formOptions.saveLoading = true;
      this.$api
        .admin_areaArchives_add(params)
        .then(res => {
          this.$message({
            message: "保存成功",
            type: "success"
          });
          this.handleFormSubmit();
          this.dialogVisible = false;
        })
        .finally(() => {
          this.formOptions.saveLoading = false;
        });
    },
    // 获取表计列表
    getMetermodel() {
      this.$api
        .admin_metermodel_getList()
        .then(res => {
          this.dialogForm.selectOption.metermodelList = res;
        })
        .catch(err => {
          console.log("err", err);
        });
    },
    // 获取价格方列表
    getPrice() {
      this.$api
        .admin_price_getList({
          areaOrg: this.queryForm.areaId
        })
        .then(res => {
          this.dialogForm.selectOption.priceList = res;
        })
        .catch(err => {
          console.log("err", err);
        });
    },
    // 获取集中器列表
    getConcent() {
      this.$api
        .admin_concent_getList({
          areaOrg: this.queryForm.areaId
        })
        .then(res => {
          this.dialogForm.selectOption.concentList = res;
        })
        .catch(err => {
          console.log("err", err);
        });
    },
    // 获取户号列表
    getHousehold() {
      this.$api
        .admin_household_getList({
          areaOrg: this.queryForm.areaId
        })
        .then(res => {
          this.dialogForm.selectOption.householdList = res;
        })
        .catch(err => {
          console.log("err", err);
        });
    },
    // 获取查询枚举
    getEquipmentType() {
      this.$api
        .admin_areaArchives_getEquipmentType()
        .then(res => {
          this.queryForm.selectOption = res.archivesFilter;
          this.dialogForm.selectOption = res;
          // 获取户号
          this.getHousehold();
          // 获取集中器
          this.getConcent();
          // 获取价格
          this.getPrice();
          // 获取表计列表
          this.getMetermodel();
        })
        .catch(err => {
          console.log("err", err);
        })
        .finally(() => {});
    },
    // 分页操作
    paginationCurrentChange(currentPage) {
      this.pagination.currentPage = currentPage;
      this.fetchData();
    },
    onAreaChange(data, node) {
      this.queryForm.areaId = data.id;
      this.queryForm.areaName = data.name;
      this.fetchData();
    },
    fetchData() {
      this.loading = true;
      this.$api
        .admin_areaArchives_getPageList({
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          areaOrg: this.queryForm.areaId,
          filterType: this.queryForm.type,
          filterValue: this.queryForm.searchVal
        })
        .then(res => {
          this.data = res.data;
          this.pagination.total = res.total;
        })
        .catch(err => {
          console.log("err", err);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleFormSubmit() {
      this.pagination.currentPage = 1;
      this.fetchData();
    }
  }
};
</script>
<style lang="scss" scoped >
.dialogInfoBox {
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
  padding: 20px 10px 10px 10px;
  border: 1px #a3a3a3 solid;
  border-radius: 4px;
  width: 800px;
  position: relative;
  .dialogInfoTitle {
    position: absolute;
    top: -10px;
    background: #fff;
    padding: 0 5px;
    font-weight: bold;
  }
  .dialogInfo {
    width: 100%;
    display: flex;
    flex-direction: row;
    border-top: 1px #a3a3a3 solid;
    padding-top: 10px;
    & > div {
      width: 50%;
      margin-bottom: 10px;
    }
  }
}
</style>
